package ucadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateBannerLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBannerLogic {
	return &UpdateBannerLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新banner
func (l *UpdateBannerLogic) UpdateBanner(in *pb.UpdateBannerConfigReq) (*pb.UpdateBannerConfigResp, error) {
	defer utils.RecoverPanic()

	var st, et *time.Time
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		st = &t
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
		et = &t
	}
	var upa *usercenter.BannerConfig
	var err error
	upa, err = l.svcCtx.BannerConfigModel.FindOne(l.ctx, in.Id)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if in.BannerName != "" {
		upa.BannerName = in.BannerName
	}
	if in.Image != "" {
		upa.BannerImage = in.Image
	}
	if in.PagePath != "" {
		upa.PagePath = in.PagePath
	}
	if st != nil {
		upa.StartTime = *st
	}
	if et != nil {
		upa.EndTime = *et
	}
	if in.Order > 0 {
		upa.BannerOrder = in.Order
	}
	if in.Url != "" {
		upa.Url = in.Url
	}
	if in.State > 0 {
		upa.State = in.State
	}
	// 更新
	err = l.svcCtx.BannerConfigModel.Update(l.ctx, upa)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	return &pb.UpdateBannerConfigResp{}, nil
}
